<template>
    <div class="video_container">
        <ZWGroup ref="ZWGroupRef" :group-id="groupId" :type="4" @submit="ChangeFun" />
        <div class="video_main">
            <div class="video_search">
                <ZwSearchForm row-num="3" :option="searchOption" @search="searchFun" @reset="reset" />
            </div>
            <div class="video_header_button">
                <FormulaBar
                    ref="FormulaBarRef"
                    :type="4"
                    @batchTag="batchTag"
                    @batchDel="openDialog"
                    @openDialog="openUploadDialog"></FormulaBar>
            </div>
            <el-scrollbar v-if="videoData.length > 0" class="video_list">
                <div class="video_content">
                    <Details
                        ref="del"
                        class="img_details_item"
                        :video-data-list="videoData"
                        @submit="refreshTable"
                        @openDialog="openUploadDialog" />
                </div>
            </el-scrollbar>
            <el-empty v-else image="/static/noData.png" description="暂无数据"></el-empty>
            <ZWPagination ref="PaginationRef" />
            <!-- 上传弹框 -->
            <Upload
                v-if="showUpload"
                ref="UploadRef"
                :type="4"
                :group-id="groupId === 'all' ? 0 : groupId"
                @submit="refreshGroup"
                @closed="showUpload = false" />
            <!-- 视频播放弹窗 -->
            <Videowicket ref="videoWicket" />
            <!-- 删除弹框 -->
            <ZWDialog v-if="Dialog" :dialog="Dialog" />
        </div>
    </div>
</template>

<script setup lang="ts">
import ZWGroup from '@/components/ZWGroup.vue';
import Search from '../../components/Search.vue';
import FormulaBar from './components/FormulaBar.vue';
import Details from './components/Details.vue';
import Videowicket from './components/videoWicket.vue';
import ZWDialog from './components/ZWDialog.vue';
import Upload from './components/Upload.vue';
import ZWPagination from './components/ZWPagination.vue';
import ZWSelectTag from '@/components/ZWSelectTag.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import { ref, reactive, onMounted, watch, computed, nextTick } from 'vue';
import { useStore } from '@/store';
import { GetVideoList } from '@/api/media';
import { batchDownLoad } from '@/api/concreation';
import { batchTagAdd, batchTagDel, getCreateList } from '@/api/common';
import bus from '@/utils/bus';
import { deepCopy } from '@/utils/helper';
import { getRandomKey, treeH, reSize } from '@/utils/utils';

import ZwSearchForm from '@/components/zw/search-form/SearchForm';

import { ElMessage, ElMessageBox } from 'element-plus';
import { endLoading, startLoading } from '@/utils/request';
const videoData = ref([]);
const checkedList = ref([]);
const ZWGroupRef: any = ref(null);
const PaginationRef: any = ref(null);
const del = ref(null);
const Dialog = ref(false);
const groupId = ref<number | string>('all');
const showUpload = ref<boolean>(false);
const UploadRef = ref();
const scrollbarHeight = ref<string>('400px');
const pageInfo = reactive({
    page_size: 15,
    page: 1
});
const selection = computed(() => {
    return store.getters['table'].tableData;
});

let params = reactive({
    page_size: pageInfo.page_size,
    page: pageInfo.page,
    group_id: groupId.value,
    title: '',
    user_id: [],
    created_time: [],
    is_radar: -1,
    tag_list: []
});

const store = useStore();

const searchOption = computed(() => {
    return [
        {
            label: '视频搜索',
            name: 'title',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入视频名称进行搜索'
        },
        {
            label: '上传者',
            name: 'user_id',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '全部',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '上传时间',
            name: 'created_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        },
        {
            label: '视频类型',
            name: 'is_radar',
            value: '',
            type: 'select',
            placeholder: '全部类型',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部类型', id: '-1' },
                        { name: '普通视频', id: '0' },
                        { name: '雷达视频', id: '1' }
                    ]);
                });
            },
            formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '标签筛选',
            name: 'tag_list',
            value: [],
            type: 'select',
            placeholder: '请选择标签',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isTagSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const defaultParams = reactive({
    title: '',
    user_id: [],
    created_time: [],
    is_radar: -1,
    tag_list: [],
    group_id: 0
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const reset = (v?: any) => {
    params = { ...params, ...defaultParams };
    GetVideo(params);
    del.value?.clearSelection();
};
const GetVideo = (p: any) => {
    startLoading();
    const res = { ...params, ...p };
    GetVideoList(res, true)
        .then(res => {
            res.data.map((item: any) => {
                item.compilesss = [
                    {
                        isShow: false,
                        name: 'statistics',
                        content: '详情'
                    },
                    {
                        isShow: false,
                        name: 'delete',
                        content: '删除'
                    },
                    {
                        isShow: false,
                        name: 'download',
                        content: '下载'
                    },
                    {
                        isShow: false,
                        name: 'write',
                        content: '编辑'
                    },
                    {
                        isShow: false,
                        name: 'copy',
                        content: '分享'
                    }
                ];
            });
            videoData.value = res.data;
            checkAll(false);
            localStorage.removeItem('videoId');
            bus.emit('pageData', res);
        })
        .finally(() => {
            endLoading();
        });
};
const refreshTable = () => {
    del.value?.clearSelection();
    ZWGroupRef.value.getGroup();
    GetVideo(params);
};
const openUploadDialog = (val?: any) => {
    showUpload.value = true;
    nextTick(() => {
        UploadRef.value.uploadTitle = '上传视频';
        UploadRef.value.uploadVisib = true;
        if (val.isEdit) {
            UploadRef.value.uploadTitle = '编辑视频';
            bus.emit('editItem', val);
        }
    });
};

const openDialog = (judge: boolean) => {
    del.value.isBatchDel();
};

const DialogChange = (judge: boolean) => {
    Dialog.value = judge;
    store.dispatch('table', {
        tableData: []
    });
    GetVideo(params);
};

const Download = () => {
    const videoId = cardId.value;
    const params = {
        material_ids: videoId,
        material_type: 4
    };

    batchDownLoad(params).then(res => {
        const a = document.createElement('a');
        a.href = res.url;
        a.click();
        del.value?.clearSelection();
    });
};

const searchFun = (form: any) => {
    params.title = form.title;
    params.created_time = form.created_time;
    params.user_id = form.user_id;
    params.tag_list = form.tag_list;
    params.is_radar = form.is_radar;
    GetVideo(params);
    del.value?.clearSelection();
};
const cardId = ref([]);
// 获取选中的图片 id
const videoId = (data: any) => {
    cardId.value = data;
};
bus.on('videoId', videoId);
const batchTag = async (data: any) => {
    startLoading();
    try {
        const arr = [];
        data.tag_ids.forEach(item => {
            arr.push(item.id);
        });
        const tag_params = {
            content_ids: cardId.value,
            tag_ids: arr,
            type: 4,
            group_id: groupId.value
        };

        if (data.defaultVal === 0) {
            await batchTagAdd(tag_params, true);
            ElMessage.success('批量打标签成功！');
            // GetVideo(params)
            del.value?.clearSelection();
        } else if (data.defaultVal === 1) {
            await batchTagDel(tag_params, true);
            ElMessage.success('批量移除标签成功！');
            // GetVideo(params)
            del.value?.clearSelection();
        }
        refreshGroup();
    } catch (error) {
        endLoading();
    }
};

const ChangeFun = (data?: any) => {
    if (data) {
        defaultParams.group_id = data?.id || 0;
        groupId.value = data?.id || 0;
    } else {
        defaultParams.group_id = groupId.value;
    }
    params.group_id = groupId.value;
    params.page = pageInfo.page;
    params.page_size = pageInfo.page_size;
    GetVideo(params);
    del.value?.clearSelection();
};

const checkAll = (value: any) => {
    checkedList.value = [];
    if (value) {
        videoData.value.forEach(item => {
            checkedList.value.push(item.id);
        });
    }
    store.dispatch('table', {
        tableData: checkedList
    });
};
//当前页
const pageChange = val => {
    del.value?.clearSelection();
    params.page = val;
    GetVideo(params);
};
// 一页显示多少
const pageSizeChange = val => {
    del.value?.clearSelection();
    params.page_size = val;
    GetVideo(params);
};
const refreshGroup = (data?: any) => {
    if (data) {
        groupId.value = data.id;
        defaultParams.group_id = data.id;
        params.group_id = data.id;
        ZWGroupRef.value.getGroup();
        ZWGroupRef.value.changeGroup({ id: data.id });
        params.page = pageInfo.page;
        params.page_size = pageInfo.page_size;
        GetVideo(params);
    } else {
        ZWGroupRef.value.getGroup();
        ZWGroupRef.value.changeGroup({ id: groupId.value });
    }
};
bus.on('Download', Download);
bus.on('search', searchFun);
bus.on('checkAll', checkAll);
bus.on('pageChange', pageChange);
bus.on('pageSizeChange', pageSizeChange);

/**
 * @description: 获取内容区域滚动高度
 * @return {*}
 */
const getScrollbarHeight = () => {
    const h = treeH('.img_details', 140);
    scrollbarHeight.value = `${h}px`;
};

onMounted(() => {
    ChangeFun();
    getScrollbarHeight();
    reSize(() => getScrollbarHeight());
});
</script>

<style lang="scss" src="./style.scss" scoped></style>
